var chinaConsumptionLevel = [
    ["贵州省", 106.707603, 26.597997, 89, 55, 67, 72, 45],
    ["云南省", 102.709129, 25.046619, 80, 88, 70, 93, 11],
    ["海南省", 109.691225, 19.047108,  55, 40, 30, 70, 69],
    ["广东省", 113.265246, 23.130964, 100, 120, 110, 111, 60],
    ["广西壮族自治区", 108.327509, 22.816721, 60, 80, 75, 67, 50]
];
//[{id: "someId1", name: "Display name 1"},   {id: "someId2", name: "Display name 2"}]
var searchSubjects = [ ]; 
//自动完成搜索框
var $inputSearch = $("#input_search");

var map, layer;
var infowin, infowinPosition;
var multiInfoWins = [];
var station220Layer,station500Layer,station800Layer;
var line220Layer,line500Layer,line800Layer;
var towerLayer;
var weatherLayer;
var iceLayer;
var affectSizeLayer;// 气象影响范围图层

// 故障分布
var faultThemeLayer;
//当前经纬度
var currentLonlat;
var currentZoomLevel;
var currentExtent;
//矩形查询
var queryRectangle;
var queryRectangleLayer;

//
var stationSelectFeature;
var weatherSelectFeature;

//var mapurl = "http://10.140.0.11:8090/iserver/services/map-china400/rest/maps/China_4326";
var mapurl = "http://10.140.0.11:8090/iserver/services/map-china_nwld/rest/maps/China_nwld_100";

var stations500 = [];
var stations220 = [];
var towerpoints = [];

var tower_size = new SuperMap.Size(16,16);
var tower_offset = new SuperMap.Pixel(-8, 0);
var tower_icon = new SuperMap.Icon('/resources/img/tower.png', tower_size, tower_offset);
var station_icon = new SuperMap.Icon('/resources/img/station2.png', new SuperMap.Size(12,12), tower_offset);


var lineData = [];
var weatherData = [];
var weatherBounds = [];

function init() {
	map = new SuperMap.Map("map",
			{
				controls : [ new SuperMap.Control.ScaleLine(),
						new SuperMap.Control.Zoom(),
//						new SuperMap.Control.LayerSwitcher(),
						new SuperMap.Control.Navigation({ // 添加导航控件到map
							dragPanOptions : {
								enableKinetic : true
							// 拖拽动画
							}
						})

				],
				projection : "EPSG:4326",
				// 设置地图的可视范围
				maxExtent : new SuperMap.Bounds(96.47831261158, 16.9636416435242, 118.82450401783,30.9821963310242),
				restrictedExtent : new SuperMap.Bounds(87.40214, 10.85752, 127.73783,39.44801)
			});
	map.numZoomLevels=15;
	//8.1c 版本才支持的方法
//	map.maxZoom(10);
//	map.minZoom(5);
	layer = new SuperMap.Layer.TiledDynamicRESTLayer("China_nwld_100", mapurl, {
		cacheEnabled : true
	}, {
		maxResolution : "auto"
	});
	layer.events.on({
		"layerInitialized" : addLayer
	});
	currentZoomLevel = map.getZoom();
	station220Layer = new SuperMap.Layer.Vector("220kV变电站");
//	station500Layer = new SuperMap.Layer.Vector("500kV变电站");
	station500Layer = new SuperMap.Layer.Markers("500kV变电站");
	station800Layer = new SuperMap.Layer.Vector("800kV变电站");
//	towerLayer = new SuperMap.Layer.Graphics( "杆塔");
	towerLayer = new SuperMap.Layer.Markers( "杆塔");
	
	line220Layer = new SuperMap.Layer.Vector("220kV线路");
	line500Layer = new SuperMap.Layer.Vector("500kV线路");
	line800Layer = new SuperMap.Layer.Vector("800kV线路");
	
	weatherLayer = new SuperMap.Layer.Vector("天气图层", {
		"radius" : 45,
		"featureWeight" : "value",
		"featureRadius" : "geoRadius"
	});
	weatherLayer.setVisibility(false);
	
	iceLayer = new SuperMap.Layer.Vector("覆冰图层", {
		"radius" : 45,
		"featureWeight" : "value",
		"featureRadius" : "geoRadius"
	});
	iceLayer.setVisibility(false);
	
	affectSizeLayer = new SuperMap.Layer.Vector("气象影响范围");
	
	createRingFaultLayer();
	createBarFaultLayer();
	
	//获取当前鼠标位置的经纬度
	map.events.on({
		"mousemove" : getMousePositionPx
	});
	
	//为map添加缩放监听
    map.events.on({'moveend':zoomMove});
	
    //为map添加点击监听
    map.events.on({'click':onMapClick});
    
    
    weatherSelectFeature=new SuperMap.Control.SelectFeature(
			[weatherLayer], {
		onSelect : onWeatherClickLisnter
	});
    //为图上的矢量图层添加选择事件(只为变电站添加)
//    stationSelectFeature = new SuperMap.Control.SelectFeature(
//			[station500Layer], {
//		onSelect : onStationClickLisnter
//	});
	
	map.addControls([weatherSelectFeature]);
//	stationSelectFeature.activate();
	weatherSelectFeature.activate();
	
	//矩形查询
	queryRectangleLayer  = new SuperMap.Layer.Vector("矩形查询图层");
	queryRectangle = new SuperMap.Control.DrawFeature(queryRectangleLayer,
			SuperMap.Handler.Box);
	queryRectangle.events.on({
		"featureadded" : queryRectangleCompleted
	});
	map.addControl(queryRectangle);
	
	getData();
	
}

function addLayer() {

	map.addLayers([ layer, 
	         towerLayer,station220Layer,station800Layer,
	         line220Layer,line500Layer,line800Layer,
	         queryRectangleLayer
	         ]);
	         
	 map.addLayers([affectSizeLayer]);// 添加气象影响范围图层
	 map.addLayers([weatherLayer]);
	 map.addLayers([iceLayer]);
	 map.addLayers([station500Layer]);
	 // 显示地图范围
	 map.setCenter(new SuperMap.LonLat(108.535465, 22.788907), 4);
	
}
function createBarFaultLayer(){
	// 创建一个柱状图（Bar）统计专题图图层
	faultThemeLayer = new SuperMap.Layer.Graph("柱状图", "Bar");

	//指定用于专题图制作的属性字段
	faultThemeLayer.themeFields = ["CON2009", "CON2010", "CON2011", "CON2012", "CON2013"];
	
	//配置图表参数
	faultThemeLayer.chartsSetting = {
			// width，height，codomain 分别表示图表宽、高、数据值域；此三项参数为必设参数
			width : 240,
			height : 100,
			codomain : [ 0, 200 ], // 允许图表展示的值域范围，此范围外的数据将不制作图表
			barStyle : {
				fillOpacity : 0.7
			}, // 柱状图中柱条的（表示字段值的图形）样式
			barHoverStyle : {
				fillOpacity : 1
			}, // 柱条 hover 样式
			xShapeBlank : [ 10, 10, 10 ], // 水平方向上的空白间距参数
			axisYTick : 4, // y 轴刻度数量
			axisYLabels : [ "120", "90", "60", "30", "0" ], // y 轴标签内容
			axisXLabels : [ "09年", "10年", "11年", "12年", "13年" ], // x 轴标签内容
			backgroundStyle : {
				fillColor : "#CCE8CF"
			}, // 背景样式
			backgroundRadius : [ 5, 5, 5, 5 ], // 背景框圆角参数
			//阴影开关 默认是打开
			showShadow : true,
			//阴影样式
			barShadowStyle : {
				shadowBlur : 8,
				shadowOffsetX : 2,
				shadowOffsetY : 2,
				shadowColor : "rgba(100,100,100,0.8)"
			},
			//按字段设置柱条样式[渐变开始颜色,渐变终止颜色] 与 faultThemeLayer.themeFields 中的字段一一对应）
			barLinearGradient : [ [ "#00FF00", "#00CD00" ],
					[ "#00CCFF", "#5E87A2" ], [ "#00FF66", "#669985" ],
					[ "#CCFF00", "#94A25E" ], [ "#FF9900", "#A2945E" ] ]
		};

	// 注册专题图 mousemove, mouseout 事件(注意：专题图图层对象自带 on 函数，没有 events 对象)
	faultThemeLayer.on("mousemove", showFaultThemeLayerWin);
	faultThemeLayer.on("mouseout", closeInfoWin);

	faultThemeLayer.setOpacity(0.9);
}
function createRingFaultLayer(){
	// 创建一个统计专题图图层-环状图图层（Ring）
	faultThemeLayer = new SuperMap.Layer.Graph("环状图图层", "Ring");

	// 指定用于专题图制作的属性字段
	faultThemeLayer.themeFields = [ "CON2009", "CON2010", "CON2011", "CON2012",
			"CON2013" ];

	// 配置图表参数
	faultThemeLayer.chartsSetting = {
		// width，height，codomain 分别表示图表宽、高、数据值域；此三项参数为必设参数
		width : 100,
		height : 100,
		codomain : [ 0, 40000 ], // 允许图表展示的值域范围，此范围外的数据将不制作图表
		innerRingRadius : 20, // 环状图内环半径，默认值：0，innerRingRadius 为 0 时，可视效果同饼图
		// 环状图扇形（表示字段值的图形）样式
		sectorStyle : {
			fillOpacity : 0.8
		},
		// 按字段设置环状图扇形 (样式与 faultThemeLayer.themeFields 数组中的字段名称一一对应)
		sectorStyleByFields : [ {
			fillColor : "#FFB980"
		}, {
			fillColor : "#5AB1EF"
		}, {
			fillColor : "#B6A2DE"
		}, {
			fillColor : "#2EC7C9"
		}, {
			fillColor : "#D87A80"
		} ],
		// 环状图扇形 hover 样式
		sectorHoverStyle : {
			fillOpacity : 1
		}
	};

	// 注册专题图 mousemove, mouseout事件(注意：专题图图层对象自带 on 函数，没有 events 对象)
	faultThemeLayer.on("mousemove", showFaultThemeLayerWin);
	faultThemeLayer.on("mouseout", closeInfoWin);
	
}
function zoomMove(){
	clearQueryStatus();
	currentZoomLevel = map.getZoom();
	currentExtent = map.getExtent();
	//console.log(currentZoomLevel+" "+currentExtent);
	
	var s220visibility = station220Layer.getVisibility();
	if(currentZoomLevel > 6){
		if(!s220visibility)
			station220Layer.setVisibility(true);
		if(weatherLayer.visibility){
			//showWeatherInfoWin();
		}
	} else {
		if(s220visibility){
			station220Layer.setVisibility(false);
		}
		if(weatherLayer.visibility){
			closeInfoWin();
		}
	}
	if(currentZoomLevel < 13){
		towerLayer.clearMarkers();
	} else {
		towerLayer.clearMarkers();
		for(var i =0; i < towerpoints.length; i++){
			if(currentExtent.contains(towerpoints[i].longitude,
					towerpoints[i].latitude,true)){
//				console.log(towerpoints[i]);
				var marker =  new SuperMap.Marker(new SuperMap.LonLat(towerpoints[i].longitude,
						towerpoints[i].latitude), tower_icon);
				marker.data = towerpoints[i];
				marker.events.on({
					"mouseover" : openTowerInfoWin,
					"mouseout" : closeInfoWin,
					"scope" : marker
				});
				
				towerLayer.addMarker(marker);
			}
		}
	}
	
}
function onWeatherClickLisnter(currentFeature){
	closeInfoWin();
	var obj = currentFeature.geometry;
	var lonlat = null;
	if(obj.x){
		lonlat = new SuperMap.LonLat(obj.x, obj.y);
	} else if(currentLonlat){
		lonlat = currentLonlat;
	}
	var type = currentFeature.data.type;
	if(type == "weather"){
		openWeatherInfoWin(currentFeature.data.value,lonlat);
	} else if(type == "faultResaon"){
		openFaultResonWin(currentFeature.data.value,lonlat);
	}
}
function onStationClickLisnter(){
	closeInfoWin();
	var marker = this;
	//打开变电站svg图
	//openStationSvgPage(marker.data.id,marker.data.name);
	//打开保信二次图
	var ps = [];
	ps.push({name:"stationId",value:marker.data.id});
	ps.push({name:"stationName",value:marker.data.name});
	ps.push({name:"svgType",value:2});
	var params = MyModal.getModalParam("/ui/map/dialog/svg.xhtml", "1200","700",JSON.stringify(ps));
	openDialog(params);
}
function onQueryObjectClickLisnter(currentFeature){
	closeInfoWin();
	var obj = currentFeature.geometry;
	var lonlat = null;
	if(obj.x){
		lonlat = new SuperMap.LonLat(obj.x, obj.y);
	} else if(currentLonlat){
		lonlat = currentLonlat;
	}
	
	var type = currentFeature.data.type;
	if(type == "station"){
		//打开变电站svg图
		openStationSvgPage(currentFeature.data.value.id,currentFeature.data.value.name);
		return;
		
	} else if(type == "acline"){
		openLineInfoWin(currentFeature.data.value,lonlat);
	} else if(type == "weather"){
		openWeatherInfoWin(currentFeature.data.value,lonlat);
	}
	
	//openPage();
	
}

function openTowerInfoWin(towerObject) {
	closeInfoWin();
	var marker = this;
	var lonlat = marker.getLonLat();
	var content =  marker.data.lineName+" "+"#"+marker.data.towerno;
	var popup = new SuperMap.Popup("chicken",
            new SuperMap.LonLat(lonlat.lon, lonlat.lat),
            null,content
           ,
            false);
	popup.closeOnMove = true;
	popup.autoSize = true;
	popup.closeBox = false;
	infowin = popup;
	map.addPopup(popup);
}
function openStationInfoWin() {
	closeInfoWin();
	var marker = this;
	var station =marker.data;
	var lonlat = marker.getLonLat();
	if(!lonlat){
		lonlat = currentLonlat;
	}
	checkPosition(lonlat);
	var content = "<div class=\"box\">"
		+"<div class=\"box-header\">"
		+ station.name
		+"</div>"
		+"<div class=\"box-body\">"
		+"<a href='javascript:void(0);' onclick='openStationPrimSvg("+station.id+")' class=\"btn btn-block btn-social btn-dropbox\">"
		+"<i class=\"fa fa-bitbucket\"></i> 一次接线图"
		+"</a>"
		+"<a href='javascript:void(0);' onclick='openStationSecondSvg("+station.id+")' class=\"btn btn-block btn-social btn-dropbox\">"
		+"<i class=\"fa fa-bitbucket\"></i> 二次接线图"
		+"</a>"
		+"</div>"
		+"</div>";
	var popup = new SuperMap.Popup("chicken",
			lonlat,
			null,content
			,
			false);
	popup.closeOnMove = true;
	popup.autoSize = true;
	popup.closeBox = false;
	infowin = popup;
	map.addPopup(popup);
}
function openStationPrimSvg(sid){
	var ps = [];
	ps.push({name:"stationId",value:sid});
	ps.push({name:"svgType",value:1});
	var params = MyModal.getModalParam("/ui/map/dialog/svg.xhtml", "1200","700",JSON.stringify(ps));
	openDialog(params);
}
function openStationSecondSvg(sid){
	var ps = [];
	ps.push({name:"stationId",value:sid});
	ps.push({name:"svgType",value:2});
	var params = MyModal.getModalParam("/ui/map/dialog/svg.xhtml", "1200","700",JSON.stringify(ps));
	openDialog(params);
}
function openStationInfoWinForSearch(marker) {
	closeInfoWin();
	var lonlat = marker.getLonLat();
	var content =  "<strong>"+marker.data.name+"</strong>";
	var popup = new SuperMap.Popup("chicken",
			new SuperMap.LonLat(lonlat.lon, lonlat.lat),
			null,content
			,
			false);
	popup.closeOnMove = true;
	popup.autoSize = true;
	popup.closeBox = false;
	infowin = popup;
	map.addPopup(popup);
}
function showWeatherInfoWin(){
	currentZoomLevel = map.getZoom();
	if(currentZoomLevel>6 && multiInfoWins.length ==0){
		var i=0;
		for(i in  weatherData){
			openMultiWeatherInfoWin(weatherData[i]);
		}
	} else {
		
	}
}
function openWeatherInfoWin(wobj,lonlat) {
	closeInfoWin();
	
	checkPosition(lonlat);
	
	var boxdiv =getBoxdiv();
	var bhead = getBoxheader();
	var bbody = getBoxbody();
	var bfooter = getBoxfooter();
	
	bhead.text(wobj.title);
	bbody.append(wobj.des);
	
	///ui/map/dialog/weatherFaultCountDialog
	var params = MyModal.getModalParam("/ui/map/dialog/weatherFaultCountDialog.xhtml", "1300");
	
	bfooter.html("<a href='javascript:void(0)' onclick='openDialog("+JSON.stringify(params)+")' class='btn btn-sm btn-info btn-flat pull-left'>预警分析</a>");
	
	bhead.css("width","200px");
	bbody.css("width","200px");
	
	boxdiv.append(bhead);
	boxdiv.append(bbody);
	boxdiv.append(bfooter);
	
	var pdiv = $("<div />");
	pdiv.append(boxdiv);
	
	var content = pdiv.html();
	var popup = new SuperMap.Popup("chicken",
			new SuperMap.LonLat(lonlat.lon, lonlat.lat),
			null,content
			,
			false);
	popup.closeOnMove = true;
	popup.autoSize = true;
	popup.closeBox = false;
	infowin = popup;
	map.addPopup(popup);
}
function openFaultResonWin(fault,lonlat) {
	closeInfoWin();
	var boxdiv =getBoxdiv();
	var bbody = getBoxbody();
	var ft = new Date(fault.faultTime); 
	bbody.append("故障时间: "+ft.toLocaleString()+"<br />");
	bbody.append("故障类型: "+fault.faultType+"<br />");
	bbody.append("故障原因: "+fault.faultReson+"<br />");
	bbody.append("故障相别: "+fault.faultPhase+"<br />");
	bbody.append("备注: "+fault.remark);
	bbody.css("width","200px");
	boxdiv.append(bbody);
	
	var pdiv = $("<div />");
	pdiv.append(boxdiv);
	
	var content = pdiv.html();
	var popup = new SuperMap.Popup("chicken",
            new SuperMap.LonLat(lonlat.lon, lonlat.lat),
            null,content
           ,
            false);
	popup.closeOnMove = true;
	popup.autoSize = true;
	popup.closeBox = false;
	infowin = popup;
	map.addPopup(popup);
}
function openMultiWeatherInfoWin(wobj) {
	var lonlat = new SuperMap.LonLat(wobj.lon,wobj.lat);
	var boxdiv =getBoxdiv();
	var bhead = getBoxheader();
	var bbody = getBoxbody();
	var bfooter = getBoxfooter();
	
	bhead.text(wobj.title);
	bbody.append(wobj.des);
	
	///ui/map/dialog/weatherFaultCountDialog
	var params = MyModal.getModalParam("/ui/map/dialog/weatherFaultCountDialog.xhtml", "1300");
	
	bfooter.html("<a href='javascript:void(0)' onclick='openDialog("+JSON.stringify(params)+")' class='btn btn-sm btn-info btn-flat pull-left'>预警分析</a>");
	
	bhead.css("width","200px");
	bbody.css("width","200px");
	
	boxdiv.append(bhead);
	boxdiv.append(bbody);
	boxdiv.append(bfooter);
	
	var pdiv = $("<div />");
	pdiv.append(boxdiv);
	
	var content = pdiv.html();
	var popup = new SuperMap.Popup(null,
			new SuperMap.LonLat(lonlat.lon, lonlat.lat),
			null,content
			,
			false);
	popup.closeOnMove = false;
	popup.autoSize = true;
	popup.closeBox = true;
	multiInfoWins.push(popup);
	map.addPopup(popup);
}

function openAllLineFault(){
	var ps = [];
	var params = MyModal.getModalParam("/ui/map/dialog/fault/faultHisDialog.xhtml", "1200", null,ps);
	openDialog(params);
}

function openLineInfoWin(lineObject,lonlat) {
	closeInfoWin();
	if(!lonlat){
		lonlat = currentLonlat;
	}
	checkPosition(lonlat);
	if(!lineObject.lineName){
		lineObject = JSON.parse(lineObject);
	}
	
	if(!lineObject.startSt){
		lineObject.startSt = "";
	}
	
	if(!lineObject.endSt){
		lineObject.endSt = "";
	}
	
	var ps = [];
	ps.push({name:"selectId",value:lineObject.lineId});
	ps.push({name:"selectName",value:lineObject.lineName});
	var params = MyModal.getModalParam("/ui/map/dialog/lineFaultHisDialog.xhtml", "1000", null,JSON.stringify(ps));
	var params2 = MyModal.getModalParam("/ui/map/dialog/protectResponseDialog.xhtml", "1200", null,JSON.stringify(ps));
	var params3 = MyModal.getModalParam("/ui/map/dialog/iceFaultDialog.xhtml", "1000", null,JSON.stringify(ps));
	
	var content = "<div class=\"box\">"
            +"<div class=\"box-header\">"
             +"线路名称："+lineObject.lineName
             +"<br/>"
             +"起始站："+lineObject.startSt
             +"<br/>"
             +"结束站："+lineObject.endSt
           +"</div>"
           +"<div class=\"box-body\">"
	           +"<a href='javascript:void(0);' onclick='showFaultReasonInMap("+JSON.stringify(lineObject)+")' class=\"btn btn-block btn-social btn-dropbox\">"
	           +"<i class=\"fa fa-eye\"></i> 查看历史故障"
	           +"</a>"
             +"<a href='javascript:void(0);' onclick='openDialog("+JSON.stringify(params)+")' class=\"btn btn-block btn-social btn-dropbox\">"
               +"<i class=\"fa fa-bar-chart\"></i> 故障历史分析"
             +"</a>"
             +"<a href='javascript:void(0);' onclick='openLineTripPage("+lineObject.lineId+")' class=\"btn btn-block btn-social btn-dropbox\">"
             +"<i class=\"fa fa-random\"></i> 跳闸统计"
             +"</a>"
             +"<a href=\""+encodeURI("/ui/map/evaluationLineData.xhtml?lineId="+lineObject.lineId+"&lineName="+escape(lineObject.lineName))+"\" \" target='_blank' class=\"btn btn-block btn-social btn-dropbox\">"
               +"<i class=\"fa fa-star\"></i> 保护动作评价"
             +"</a>"
             +"<a href='javascript:void(0);' onclick='openDialog("+JSON.stringify(params2)+")' class=\"btn btn-block btn-social btn-dropbox\">"
             +"<i class=\"fa  fa-circle-thin\"></i> 保护响应特性"
             +"</a>"
             +"<a href='javascript:void(0);' onclick='openDialog("+JSON.stringify(params3)+")' class=\"btn btn-block btn-social btn-dropbox\">"
               +"<i class=\"fa  fa-clock-o\"></i> 覆冰历史记录"
             +"</a>"
           +"</div>"
         +"</div>";
	var popup = new SuperMap.Popup("chicken",
			lonlat,
			null,content
			,
			false);
	popup.closeOnMove = true;
	popup.autoSize = true;
	popup.closeBox = false;
	infowin = popup;
	map.addPopup(popup);
}
function openStationMenuWin(station,lonlat) {
	closeInfoWin();
	if(!lonlat){
		lonlat = currentLonlat;
	}
	checkPosition(lonlat);
	if(!station.id){
		station = JSON.parse(station);
	}
	var ps = [];
	ps.push({name:"stationId",value:marker.data.id});
	var params = MyModal.getModalParam("/ui/map/dialog/svg.xhtml", "1200","700",JSON.stringify(ps));
	var content = "<div class=\"box\">"
		+"<div class=\"box-header\">"
		+ station.name
		+"</div>"
		+"<div class=\"box-body\">"
		+"<a href='javascript:void(0);' onclick='openDialog("+JSON.stringify(params)+")' class=\"btn btn-block btn-social btn-dropbox\">"
		+"<i class=\"fa fa-bitbucket\"></i> 一次接线图"
		+"</a>"
		+"<a href=\""+encodeURI("/ui/map/line/lineTripList.xhtml?id="+station.lineId+"&name="+escape(station.lineName))+"\" \" target='_blank' class=\"btn btn-block btn-social btn-dropbox\">"
		+"<i class=\"fa fa-bitbucket\"></i> 二次接线图"
		+"</a>"
		+"<a href=\""+encodeURI("/ui/map/evaluationLineData.xhtml?lineId="+station.lineId+"&lineName="+escape(station.lineName))+"\" \" target='_blank' class=\"btn btn-block btn-social btn-dropbox\">"
		+"<i class=\"fa fa-dropbox\"></i> 保护动作评价"
		+"</a>"
		+"</div>"
		+"</div>";
	var popup = new SuperMap.Popup("chicken",
			lonlat,
			null,content
			,
			false);
	popup.closeOnMove = true;
	popup.autoSize = true;
	popup.closeBox = false;
	infowin = popup;
	map.addPopup(popup);
}
function getBoxdiv(){ return $("<div />",{"class": "box"});};
function getBoxheader(){return $("<div />",{"class": "box-header"});};
function getBoxbody(){return $("<div />",{"class": "box-body"});};
//<div class="box-footer clearfix">
//<a href="javascript:void(0)" class="btn btn-sm btn-info btn-flat pull-left">Place New Order</a>
//<a href="javascript:void(0)" class="btn btn-sm btn-default btn-flat pull-right">View All Orders</a>
//</div>
function getBoxfooter(){return $("<div />",{"class": "box-footer clearfix"});};
function getBoxbtnItem (){return $("<button />",{"class": "btn btn-default btn-block btn-flat","type":"button"});};
function getBoxli(){return $("<i />",{"class": "fa fa-code-fork"});};
function checkPosition(lonlat){
	var mapcenter = map.getCenter();
	if(lonlat.lat < mapcenter.lat){
		lonlat.lat = mapcenter.lat;
	}
}
function openSelectLineWin(vectors) {
	closeInfoWin();
	if(vectors && vectors.length > 0){
		var lonlat = currentLonlat;
		checkPosition(lonlat);
		
		var boxdiv =getBoxdiv();
		var bhead = getBoxheader();
		var bbody = getBoxbody();
		
		for(var i=0;i < vectors.length;i++){
			var btnitem = $("<button />",{
				"class": "btn btn-default btn-block btn-flat",
				"type":"button",
				"onclick":"openLineInfoWin('"+JSON.stringify(vectors[i].data.value)+"')"
					});
			btnitem.text(vectors[i].data.value.lineName);
//			btnitem.html("<button type='button' class='btn btn-default btn-block btn-flat'>"+vectors[i].data.value.lineName)+"</button>";
//			btnitem.on("click",function(){ 
//				openLineInfoWin(vectors[i].data.value,lonlat);
//				});
			bbody.append(btnitem);
		}
		
		bhead.text("选择线路");
		boxdiv.append(bhead);
		boxdiv.append(bbody);
		
		var pdiv = $("<div />");
		pdiv.append(boxdiv);
		var content = pdiv.html();
		var popup = new SuperMap.Popup("chicken",
				lonlat,
				null,content
				,
				false);
		popup.closeOnMove = true;
		popup.autoSize = true;
		popup.closeBox = false;
		infowin = popup;
		map.addPopup(popup);
	}
}
//关闭信息框
function closeInfoWin() {
	if (infowin) {
		try {
			infowin.hide();
			infowin.destroy();
		} catch (e) {
		}
	}
	if(multiInfoWins.length>0){
		var i=0;
		for(i in multiInfoWins){
			try {
				multiInfoWins[i].hide();
				multiInfoWins[i].destroy();
			} catch (e) {
			}
		}
		multiInfoWins = [];
	}
}
function getData() {
//	getStations();
//	getLineByVoltage();
	getWeatherWarningByDate();
	
	$inputSearch.typeahead({
	  source: searchSubjects,
	  autoSelect: false
	});
//	getLineById();
}
function getStations(){
	 $.getJSON("/rest/getStations/500",function(result){
		stations500 = result;
		draw_station(500);
	});
}
function getLineByVoltage(){
	 $.getJSON("/rest/getLineByVoltage/500",function(result){
		lineData = result;
		draw_acline();
	 });
}

function getWeatherWarningByDate(){
	$.getJSON("/rest/getWeatherWarningByDate/2016-09-16 09:53:18",function(result){
		weatherData = result;
		$("#weaterhNum").text(weatherData.length);
		$.getJSON("/rest/getWeatherWarningBoundByDate/2016-09-16 09:53:18",function(result){
			weatherBounds = result;
		});
	});
}
function getWeatherWarningBounds(cityid){
	var bounds = [];
	for(var i in weatherBounds){
		var bd = weatherBounds[i];
		if(bd[0] == cityid){
			bounds.push(JSON.parse(bd[1]));
		}
	}
	return bounds;
}

function draw_station(voltage) {
	var features = [];
	if(500 == voltage){
		draw500(stations500);
//		for ( var i = 0; stations500.length > i; i++) {
//			features.push(draw500(stations500[i]));
//		}
//		station500Layer.addFeatures(features);
	} else if(220 == voltage) {
		for ( var i = 0; stations220.length > i; i++) {
			features.push(draw220(stations220[i]));
		}
		station220Layer.addFeatures(features);
	}
}
function draw_weather(){
	
	
}

function draw_acline() {
	var features = [];
	for ( var i = 0; lineData.length > i; i++) {
		var points = [];
		var towers = lineData[i].towers;
		//起始站坐标
		if(lineData[i].stLonlat[0] != 0){
			var point1 = new SuperMap.Geometry.Point(lineData[i].stLonlat[0],
					lineData[i].stLonlat[1]);
			points.push(point1);
		}
		for ( var j = 0; j < towers.length; j++) {
			var point = new SuperMap.Geometry.Point(towers[j].longitude,
					towers[j].latitude);
			points.push(point);
			towerpoints.push(towers[j]);
		}
		if(lineData[i].etLonlat[0] != 0){
			var point2 = new SuperMap.Geometry.Point(lineData[i].etLonlat[0],
					lineData[i].etLonlat[1]);
			points.push(point2);
		}
		var line = new SuperMap.Geometry.LineString(points);
		var linecVector = new SuperMap.Feature.Vector(line);
		linecVector.style = {
			strokeColor : "green",
			strokeWidth : 2
		};
		linecVector.data.type="acline";
		linecVector.data.value=lineData[i];
		features.push(linecVector);
		addToSearchs(lineData[i].lineName,lineData[i].lineName,true);
		
	}
	line500Layer.addFeatures(features);
}
function draw_acline_one(tdata) {
	var features = [];
	var points = [];
	var towers = tdata.towers;
	//起始站坐标
	var point1 = new SuperMap.Geometry.Point(tdata.stLonlat[0],
			tdata.stLonlat[1]);
	points.push(point1);
	for ( var j = 0; j < towers.length; j++) {
		var point = new SuperMap.Geometry.Point(towers[j].longitude,
				towers[j].latitude);
		points.push(point);
		//towerpoints.push(towers[j]);
	}
	var point2 = new SuperMap.Geometry.Point(tdata.etLonlat[0],
			tdata.etLonlat[1]);
	points.push(point2);
	var line = new SuperMap.Geometry.LineString(points);
	var linecVector = new SuperMap.Feature.Vector(line);
	linecVector.style = {
		strokeColor : "red",
		strokeWidth : 4
	};
	linecVector.data.type="acline";
	linecVector.data.value=tdata;
	features.push(linecVector);
	line500Layer.addFeatures(features);
}

function draw220(station) {
	//点对象
	var lon = station.longitude;
	var lat = station.latitude;
	//var name = station.name;
	
	var point = new SuperMap.Geometry.Point(lon, lat);
	var pointVector = new SuperMap.Feature.Vector(point);
	pointVector.style = {
		fillColor : "blue",
		strokeColor : "red",
//		label : name,
//		labelAlign : 'cb',//{String} 标签对齐，是由两个字符组成的字符串，如：”lt”, “cm”, “rb”， 其中第一个字符代表水平方向上的对齐，”l”=left, “c”=center, “r”=right； 第二个字符代表垂直方向上的对齐，”t”=top, “m”=middle, “b”=bottom。
//		labelYOffset : 6,//{Number} 标签在y轴方向的偏移量。
		pointRadius : 5
	};
	pointVector.data.type="station";
	pointVector.data.value=station;
	return pointVector;
}

function draw500(station) {
//	//点对象
//	var lon = station.longitude;
//	var lat = station.latitude;
//	var name = station.name;
//	
//	var point = new SuperMap.Geometry.Point(lon, lat);
//	var pointVector = new SuperMap.Feature.Vector(point);
//	pointVector.style = {
//		fillColor : "red",
//		strokeColor : "blue",
//		label : name,
//		labelAlign : 'cb',//{String} 标签对齐，是由两个字符组成的字符串，如：”lt”, “cm”, “rb”， 其中第一个字符代表水平方向上的对齐，”l”=left, “c”=center, “r”=right； 第二个字符代表垂直方向上的对齐，”t”=top, “m”=middle, “b”=bottom。
//		labelYOffset : 6,//{Number} 标签在y轴方向的偏移量。
//		pointRadius : 6
//	};
//	pointVector.data.type="station";
//	pointVector.data.value=station;
//	return pointVector;
	for ( var i = 0; stations500.length > i; i++) {
		if(stations500[i].longitude && stations500[i].longitude != 0){
			var marker =  new SuperMap.Marker(new SuperMap.LonLat(stations500[i].longitude,
					stations500[i].latitude), station_icon);
			marker.data = stations500[i];
			marker.events.on({
//				"mouseover" : openStationInfoWin,
				"click" : onStationClickLisnter,
				"scope" : marker
			});
			station500Layer.addMarker(marker);
			addToSearchs(stations500[i].name,stations500[i].name,true);
		}
	}
}
function addToSearchs(key,value,isTransPinYin){
	searchSubjects.push({id: key, name: value});
	if(isTransPinYin){
		var pinyinkey = pinyinUtil.getFirstLetter(key);
		searchSubjects.push({id: pinyinkey, name: value});
	};
}


function clearFeatures() {
	lineLayer.removeAllFeatures();
}
function clearQueryStatus() {
	queryRectangleLayer.removeAllFeatures();
	queryRectangle.deactivate();
}
function openPage(){
	var a = $("<a href='http://www.baidu.com' target='_blank'>百度</a>").get(0);
    var e = document.createEvent('MouseEvents');
    e.initEvent( 'click', true, true );
    a.dispatchEvent(e);
}
function openStationSvgPage(sid,sname){
	var urlstr = encodeURI("/ui/map/svg.xhtml?stationId="+sid+"&stationName="+escape(sname));
	var a = $("<a href='"+urlstr+"' target='_blank'>南网大数据</a>").get(0);
	var e = document.createEvent('MouseEvents');
	e.initEvent( 'click', true, true );
	a.dispatchEvent(e);
}
function openLineTripPage(id,name){
	var ps = [];
	ps.push({name:"id",value:id});
	var params = MyModal.getModalParam("/ui/map/line/lineTripList.xhtml", "1200","700",JSON.stringify(ps));
	openDialog(params);
}
function getMousePositionPx(e) {
	infowinPosition = e.xy.clone();
	// 偏移
	infowinPosition.x += 40;
	infowinPosition.y -= 25;
	currentLonlat = map.getLonLatFromPixel(new SuperMap.Pixel(e.xy.x, e.xy.y));
//	console.log(currentLonlat);
}
function onMapClick(e) {
	if(infowin){
		return;
	}
	infowinPosition = e.xy.clone();
	// 偏移
	infowinPosition.x += 40;
	infowinPosition.y -= 25;
	currentLonlat = map.getLonLatFromPixel(new SuperMap.Pixel(e.xy.x, e.xy.y));
	var sp = 0.01;
	if(map.getZoom() > 10){
		sp = 0.002;
	}
	var bounds = new SuperMap.Bounds(currentLonlat.lon-sp,currentLonlat.lat-sp,currentLonlat.lon+sp,currentLonlat.lat+sp); 
	findLineByBounds(bounds);
	
}
//画矩形
function drawQueryRectangle() {
	//先清除上次的显示结果
	clearQueryStatus();
	queryRectangle.activate();
}
function queryRectangleCompleted(obj) {
	queryRectangle.deactivate();
	//先清除上次的显示结果
	//clearQueryStatus();

	var feature = obj.feature;
	var queryBounds = feature.geometry.bounds;
	findLineByBounds(queryBounds);
	
}
function findLineByBounds(queryBounds){
	var line500features = line500Layer.features;
	var intersectsVector = [];
	
	for(var i=0;i<line500features.length;i++){
		var lineVector = line500features[i];
		var linestrings = lineVector.geometry.components;
		for(var j =0; j < linestrings.length;j++){
			var bounds = linestrings[j].bounds;
			//判断两个几何图形是否相交。
			var isIntersects = bounds.intersectsBounds(
					queryBounds
			);
			if(isIntersects){
				intersectsVector.push(lineVector);
				break;
			}
		}
	}
	if(intersectsVector && intersectsVector.length > 0){
		if(intersectsVector.length == 1 ){
			onQueryObjectClickLisnter(intersectsVector[0]);
		} else {
			openSelectLineWin(intersectsVector);
		}
	}
}
function createIceLayer(){
	var visible = iceLayer.getVisibility();
	if(visible){
		clearIceLayer();
		return ;
	}
	iceLayer.setVisibility(true);
	getIceHistory();
	
}
// 不同气象按类别在地图上显示
var weatherArr = [];
var kind = [];
function weatherType(weatherType,gif){
	weatherArr.length = 0;
	var visible = weatherLayer.getVisibility();
	if(visible){
		clearWeatherLayer();
		affectSizeLayer.removeAllFeatures();// 清除气象信息
		if(kind[kind.length-1] == weatherType){
			return;
		}
	}
	showAffectDiv();
	var heatPoints = [];
	for(var i=0; i<weatherData.length; i++){
		var type = weatherData[i].atype;
		if(type == weatherType){
			weatherArr.push(i);
			kind.push(type);
		}
	}
	for(var i=0; i<weatherArr.length; i++){
		var points = new SuperMap.Geometry.Point(weatherData[weatherArr[i]].lon,weatherData[weatherArr[i]].lat);// 圆心位置
		heatPoints[i] = new SuperMap.Feature.Vector(
				points,
	            null,
	            {
	                externalGraphic: "/resources/img/weather/"+gif,
	                graphicWidth: 50,
	                graphicHeight: 50,
	                graphicOpacity:1,
	            }
			);
		heatPoints[i].data.type="weather";
		heatPoints[i].data.value=weatherData[i];
		var wbounds = getWeatherWarningBounds(weatherData[weatherArr[i]].cityId);
		if(wbounds){
			var lrs = [];
			for(var b in wbounds){
				var ps =[];
				var bd = wbounds[b];
				for(var j in bd){
					var p = new SuperMap.Geometry.Point(bd[j].lng,bd[j].lat);
					ps.push(p);
				}
				var linearRings = new SuperMap.Geometry.LinearRing(ps);
				lrs.push(linearRings);
			}
			var region = new SuperMap.Geometry.Polygon(lrs);
			var bv = new SuperMap.Feature.Vector(region);
			bv.style = {
					strokeColor:"#FA6271",
					strokeType:"dashed",
					fillColor:new SuperMap.Style.RadialGradient(0.5,0.5,0.5,0.5,0.5,[{offset:0.0,color:"white",opacity:1},{offset:1.0,color:"#FA6271",opacity:0.3}]),// #AAE0B9
					fillOpacity:0.8
			};
			affectSizeLayer.addFeatures([bv]);
		} else {
			var circleP = createCircle(points,0.5,100,360,10);// 气象预警影响范围半径50公里
			var circleVector = new SuperMap.Feature.Vector(circleP);
			circleVector.style = {
					strokeColor:"#FA6271",
					strokeType:"dashed",
					fillColor:new SuperMap.Style.RadialGradient(0.5,0.5,0.5,0.5,0.5,[{offset:0.0,color:"white",opacity:1},{offset:1.0,color:"#FA6271",opacity:0.3}]),// #AAE0B9
					fillOpacity:0.8
			};
			affectSizeLayer.addFeatures([circleVector]);// 添加到气象影响范围图层
		}
		weatherAffectTbDataset = get50kmDateSet(points);
	}
	weatherLayer.addFeatures(heatPoints);
	weatherLayer.setVisibility(true);
	showWeatherInfoWin();
	showWeatherAffectWin(weatherAffectTbDataset);
};
var visible = false;
function createWeatherLayer() {
	visible = weatherLayer.getVisibility();
	if(visible){
		clearWeatherLayer();
		affectSizeLayer.removeAllFeatures();// 清除气象信息
		return ;
	}
	showAffectDiv();
	var heatPoints = [];
	var num = weatherData.length;
	for ( var i = 0; i < num; i++) {
		var gif = "ld1.gif";
		var type = weatherData[i].atype;
		if(type == '森林火险'){
			gif="fire1.gif";
		} else if(type == '雷电'){
			gif="leidian1.gif";
		} else if(type == '台风'){
			gif="taifeng1.gif";
		} else if(type == '暴雨'){
			gif="baoyu1.gif";
		} else if(type == '高温'){
			gif="gaowen1.gif";
		}
		var points = new SuperMap.Geometry.Point(weatherData[i].lon,weatherData[i].lat);// 圆心位置
		heatPoints[i] = new SuperMap.Feature.Vector(
				points,
	            null,
	            {
	                externalGraphic: "/resources/img/weather/"+gif,
	                graphicWidth: 50,
	                graphicHeight: 50,
	                graphicOpacity:1,
	            }
			);
		heatPoints[i].data.type="weather";
		heatPoints[i].data.value=weatherData[i];
		var wbounds = getWeatherWarningBounds(weatherData[i].cityId);
		if(wbounds){
			var lrs = [];
			for(var b in wbounds){
				var ps =[];
				var bd = wbounds[b];
				for(var j in bd){
					var p = new SuperMap.Geometry.Point(bd[j].lng,bd[j].lat);
					ps.push(p);
				}
				var linearRings = new SuperMap.Geometry.LinearRing(ps);
				lrs.push(linearRings);
			}
			var region = new SuperMap.Geometry.Polygon(lrs);
			var bv = new SuperMap.Feature.Vector(region);
			bv.style = {
					strokeColor:"#FA6271",
					strokeType:"dashed",
					fillColor:new SuperMap.Style.RadialGradient(0.5,0.5,0.5,0.5,0.5,[{offset:0.0,color:"white",opacity:1},{offset:1.0,color:"#FA6271",opacity:0.3}]),// #AAE0B9
					fillOpacity:0.8
			};
			affectSizeLayer.addFeatures([bv]);
		} else {
			var circleP = createCircle(points,0.5,100,360,10);// 气象预警影响范围半径50公里
			var circleVector = new SuperMap.Feature.Vector(circleP);
			circleVector.style = {
					strokeColor:"#FA6271",
					strokeType:"dashed",
					fillColor:new SuperMap.Style.RadialGradient(0.5,0.5,0.5,0.5,0.5,[{offset:0.0,color:"white",opacity:1},{offset:1.0,color:"#FA6271",opacity:0.3}]),// #AAE0B9
					fillOpacity:0.8
			};
			affectSizeLayer.addFeatures([circleVector]);// 添加到气象影响范围图层
		}
		weatherAffectTbDataset = get50kmDateSet(points);
	}
	weatherLayer.addFeatures(heatPoints);
	weatherLayer.setVisibility(true);
	showWeatherInfoWin();
	showWeatherAffectWin(weatherAffectTbDataset);
};
// 画圆：气象影响范围
function createCircle(origin,radius,sides,r,angel){
	var rR = r*Math.PI/(180*sides);
	var rotatedAngle, x, y;
	var points = [];
	for(var i = 0; i < sides; i++){
		rotatedAngle = rR*i;
		x = origin.x + (radius * Math.cos(rotatedAngle));
		y = origin.y + (radius * Math.sin(rotatedAngle));
		points.push(new SuperMap.Geometry.Point(x, y));
	}
	rotatedAngle = r*Math.PI/180;
	x = origin.x + (radius * Math.cos(rotatedAngle));
	y = origin.y + (radius * Math.sin(rotatedAngle));
	points.push(new SuperMap.Geometry.Point(x, y));
	var ring = new SuperMap.Geometry.LinearRing(points);
	ring.rotate(parseFloat(angel),origin);
	var geo = new SuperMap.Geometry.Collection([ring]);
	geo.origin = origin;
	geo.radius = radius;
	geo.r = r;
	geo.angel = angel;
	geo.sides = sides;
	geo.polygonType = "Curve";
	return geo;
};
function showWeatherAffectWin(dataset){
	if(dataset){
		weatherAffectTb.setDataSet(dataset).show();
	}
}
function showIceWin(dataset){
	if(dataset){
		showIceDiv();
		iceTb.rows.add(dataset);
		iceTb.draw();
	}
}

function getIceFault(){
	 $.getJSON("/rest/ice/getIceFault",function(result){
		iceFault = result;
		getIceTbDataSet();
	});
}
function getIceHistory(){
	if(iceHistory && iceHistory.length>0){
		getIceTbDataSet();
	} else {
		 $.getJSON("/rest/ice/getIce",function(result){
			iceHistory = result;
			getIceFault();
		});
	}
}
function getIceTbDataSet(){
	var imap = new Map();
	var i = 0;
	for(i in iceHistory){
		var id = iceHistory[i][0];
		var ds = imap.get(id);
		if(!ds){
			ds = [];
			imap.put(id, ds);
		}
		ds.push(iceHistory[i][1],iceHistory[i][2]+"次","0次");
	}
	i=0;
	for(i in iceFault){
		var id = iceFault[i][0];
		var ds = imap.get(id);
		if(ds){
			ds[2] = iceFault[i][1]+"次";
		}
	}
	var mykeys = imap.keys;
	i=0;
	for(i in mykeys){
		iceTbDataset.push(imap.get(mykeys[i]));
	}
	showIceWin(iceTbDataset);
}

function get50kmDateSet(points) {
	
	//console.dir(currentLonlat);
	var sp = 0.5;
	var bounds = new SuperMap.Bounds(points.x-sp,points.y-sp,points.x+sp,points.y+sp);
	var dataset = [];
	//console.dir(bounds);
	var lineTowerMap = findLineByWeatherBounds(bounds);
	if(lineTowerMap){
		var lns = lineTowerMap.keys;
		var i = 0;
		for(i in lns){
			var tws = lineTowerMap.get(lns[i]);
			dataset.push([lns[i],"T"+tws[0]+"---"+"T"+tws[tws.length-1],parseInt(Math.random()*10)+"%","line",lns[i]]);
		}
	}
	var stArray = findStationByWeatherBounds(bounds);
	if(stArray){
		var i = 0;
		for(i in stArray){
			var st = stArray[i];
			dataset.push([st.name,"",parseInt(Math.random()*10)+"%","st",st]);
		}
	}
	return dataset;
}
function getRandom10(){
	
}
function findLineByWeatherBounds(queryBounds){
	
	var currentExtent = queryBounds;
	var lineTowerMap = new Map();
	for(var i =0; i < towerpoints.length; i++){
		if(currentExtent.contains(towerpoints[i].longitude,
				towerpoints[i].latitude,true)){
			var ts = lineTowerMap.get(towerpoints[i].lineName);
			if(!ts){
				ts = [];
				lineTowerMap.put(towerpoints[i].lineName, ts);
			}
			ts.push(towerpoints[i].towerno);
		}
	}
	return lineTowerMap;
}
function findStationByWeatherBounds(queryBounds){
	
	var currentExtent = queryBounds;
	var containsSt = [];
	for(var i =0; i < stations500.length; i++){
		if(currentExtent.contains(stations500[i].longitude,
				stations500[i].latitude,true)){
			containsSt.push(stations500[i]);
		}
	}
	return containsSt;
}
var weatherAffectTbDataset =[] ;	
var weatherAffectTb = new MyTable('datatable',["线路","杆塔","受影响概率"]);
weatherAffectTb.onRowClick(function(data){
	if(data){
    	$("#input_search").val(data[0]);
    	searchObj();
	}
});
//var weatherAffectTb = $('#datatable').DataTable( {
//	"language": {
//        	"url": "/resources/plugins/datatables/Chinese.json"
//    },
//    scrollY: 600,
//    scrollX: 350,
//    "paging": false,
//    "lengthChange": false,
//    "searching": false,
//    "ordering": false,
//    "info": false,
//    "autoWidth": false,
//    columns: [
//	          { title: "线路" },
//	          { title: "杆塔" },
//	          { title: "受影响概率" }
//	          ]
//} );
//$('#datatable tbody').on( 'click', 'tr', function () {
//    if ( $(this).hasClass('selected') ) {
//        $(this).removeClass('selected');
//    }
//    else {
//    	weatherAffectTb.$('tr.selected').removeClass('selected');
//        $(this).addClass('selected');
//        var data = weatherAffectTbDataset[this.rowIndex-1];
//        if(data){
//        	$("#input_search").val(data[0]);
//        	searchObj();
//        }
//    }
//} );
var iceTbDataset =[] ;	
var iceFault=[];
var iceHistory=[];
var iceTb = $('#icetable').DataTable( {
	"language": {
        	"url": "/resources/plugins/datatables/Chinese.json"
    },
    scrollY: 600,
    "paging": false,
    "lengthChange": false,
    "searching": false,
    "ordering": false,
    "info": false,
    "autoWidth": false,
    columns: [
	          { title: "线路" },
	          { title: "覆冰" },
	          { title: "故障" }
	          ]
} );
$('#icetable tbody').on( 'click', 'tr', function () {
    if ( $(this).hasClass('selected') ) {
        $(this).removeClass('selected');
    }
    else {
    	iceTb.$('tr.selected').removeClass('selected');
        $(this).addClass('selected');
        var data = iceTbDataset[this.rowIndex-1];
        if(data){
        	$("#input_search").val(data[0]);
        	searchObj();
        }
    }
} );
function searchObj(){
	var name = $("#input_search").val();
	if(name && name.length>0){
		var sts = station500Layer.markers;
		for(var i =0 ; i < sts.length;i++){
			var s = sts[i].data;
			if(s.name.indexOf(name) > -1){
				map.setCenter(sts[i].getLonLat(),10);
				openStationInfoWinForSearch(sts[i]);
				return;
			}
		}
		var lines = line500Layer.features;
		for(var i =0 ; i < lines.length;i++){
			var obj = lines[i].data.value;
			if(obj.lineName.indexOf(name) > -1){
				lines[i].style = {
						strokeColor : "red",
						strokeWidth : 5
				};
				map.zoomToExtent(lines[i].geometry.bounds);
				return;
			}
		}
	}
}
function searchSelectObj(name){
	if(name && name.length>0){
		var sts = station500Layer.markers;
		for(var i =0 ; i < sts.length;i++){
			var s = sts[i].data;
			if(s.name.indexOf(name) > -1){
				map.setCenter(sts[i].getLonLat(),10);
				openStationInfoWinForSearch(sts[i]);
				return;
			}
		}
		var lines = line500Layer.features;
		for(var i =0 ; i < lines.length;i++){
			var obj = lines[i].data.value;
			if(obj.lineName.indexOf(name) > -1){
				lines[i].style = {
						strokeColor : "red",
						strokeWidth : 5
				};
				map.zoomToExtent(lines[i].geometry.bounds);
				return;
			}
		}
	}
}
function showFaultReasonInMap(lineObj){
	var linename = lineObj.lineName;
	 $.getJSON("/rest/getLineFaultCountByName/"+linename,function(result){
			var lineFaultData = result;
			showFaultIocn(lineFaultData,lineObj);
			searchSelectObj(linename);
		 });
}
function showFaultIocn(ld,lineObj){
	var fts = [];
	var lfs =[];
	for(var i in ld){
		var remaker = ld[i].remark;
		var tapos = remaker.indexOf("塔");
//		var tnum = remaker.replace(/[^0-9]/ig,"");
		var tnum =  parseInt(remaker.substring(0,tapos).replace(/#/,''));
		var towerno = tnum+"";
		if(towerno.substr(0,1) == "0"){
			towerno = towerno.substr(1);
		}
		fts.push(towerno);
		lfs.push(ld[i]);
	}
	var towers = lineObj.towers;
	var showTowers = [];
	for ( var j in towers) {
		var t = towers[j];
		for(var f in fts){
			if (fts[f] == t.towerno) {
				var obj = {t:towers[j],f:lfs[f]};
				showTowers.push(obj);
			}
		}
	}
	drawFaultIcon(showTowers);
}
function drawFaultIcon(towers){
	clearWeatherLayer();
	multiInfoWins = [];
	var heatPoints = [];
	for ( var i  in towers ) {
		var gif = "baoyu1.gif";
		var type = towers[i].f.faultReson;
		if(type == '山火'){
			gif="fire1.gif";
		} else if(type == '雷击'){
			gif="leidian1.gif";
		} else if(type == '风偏'){
			gif="dafeng1.gif";
		} else if(type == '暴雨'){
			gif="baoyu1.gif";
		} else if(type == '高温'){
			gif="gaowen1.gif";
		} 
		var points = new SuperMap.Geometry.Point(towers[i].t.longitude,towers[i].t.latitude);
		heatPoints[i] = new SuperMap.Feature.Vector(
				points,
                null,
                {
                    externalGraphic: "/resources/img/weather/"+gif,
                    graphicWidth: 50,
                    graphicHeight: 50,
                    graphicOpacity:1,
                }
			);
		heatPoints[i].data.type="faultResaon";
		heatPoints[i].data.value=towers[i].f;
		showMulitFramedCloud(new SuperMap.LonLat(towers[i].t.longitude,towers[i].t.latitude),towers[i].t.towerno);
		//console.dir(points);
	}
	weatherLayer.addFeatures(heatPoints);
	weatherLayer.setVisibility(true);
}
//id	{String} 弹窗的唯一标识，如设为null，则将会自动生成。
//lonlat	{SuperMap.LonLat} 地图上弹窗显示的位置。
//contentSize	{SuperMap.Size} 弹窗内容的大小。
//contentHTML	{String} 弹窗中显示的一个HTML要素的字符串。
//closeBox	{Boolean} 在弹出窗口的里面是否显示关闭窗。
//closeBoxCallback	{Function} 关闭弹窗触发该回调函数。
function showMulitPopWinNormal(lonlat,content){
	var popup = new SuperMap.Popup(null,lonlat,	null,content,false);
	popup.closeOnMove = false;
	multiInfoWins.push(popup);
	map.addPopup(popup);
}
//id	{String} 弹窗的唯一标识，如设为null，则将会自动生成。
//lonlat	{SuperMap.LonLat} 地图上弹窗显示的位置。
//contentSize	{SuperMap.Size} 弹窗内容的大小。
//contentHTML	{String} 弹窗中显示的一个HTML要素的字符串。
//closeBox	{Boolean} 在弹出窗口的里面是否显示关闭窗。
//closeBoxCallback	{Function} 关闭弹窗触发该回调函数。
function showMulitPopWinAnchored(lonlat,content){
	var popup = new SuperMap.Popup.Anchored(null,lonlat,new SuperMap.Size(80,20),content,null,false,null);
	popup.closeOnMove = false;
	multiInfoWins.push(popup);
	map.addPopup(popup);
}
function showMulitFramedCloud(lonlat,content){
//	var offset = new SuperMap.Pixel(-(size.w/2), -size.h);
//	var icon = new SuperMap.Icon(null, size, offset); 
	var contentHTML = "<div style='width:80px;font-size:12px; opacity: 0.8'>";
	contentHTML += content;
	contentHTML += "</div>";
	var popup = new SuperMap.Popup.FramedCloud("chicken",
			lonlat,
			new SuperMap.Size(80,20),
			contentHTML,
			null,
			false,
			null);
	multiInfoWins.push(popup);
	map.addPopup(popup);
}
function clearIceLayer(){
	iceLayer.setVisibility(false);
	iceTb.clear();
	$("#iceDiv").css("display","none");
}
function clearWeatherLayer() {
	weatherLayer.removeAllFeatures();
	closeInfoWin();
	weatherLayer.setVisibility(false);
//	weatherAffectTb.clear();
	$("#affectObjDiv").css("display","none");
}
var themeLayerShow = false;
function addRingThemeLayer() {
	clearThemeLayer();
	if(themeLayerShow){
		themeLayerShow = false;
		return;
	}
	createRingFaultLayer();
	
	var features = [];
	for ( var i = 0, len = chinaConsumptionLevel.length; i < len; i++) {
		// 省居民消费水平（单位：元）信息
		var provinceInfo = chinaConsumptionLevel[i];
		var geo = new SuperMap.Geometry.Point(provinceInfo[1],
				provinceInfo[2]);
		var attrs = {};
		attrs.NAME = provinceInfo[0];
		attrs.CON2009 = provinceInfo[3];
		attrs.CON2010 = provinceInfo[4];
		attrs.CON2011 = provinceInfo[5];
		attrs.CON2012 = provinceInfo[6];
		attrs.CON2013 = provinceInfo[7];

		var fea = new SuperMap.Feature.Vector(geo, attrs);
		features.push(fea);
	}

	faultThemeLayer.addFeatures(features);
	themeLayerShow = true;
	 map.addLayers([faultThemeLayer]);
}

// 清除专题图层中的内容
function clearThemeLayer() {
	if(faultThemeLayer && faultThemeLayer.charts.length > 0){
		faultThemeLayer.clear();
		map.removeLayer(faultThemeLayer);
		closeInfoWin();
	}
}

// 显示环状图弹出窗口
function showFaultThemeLayerWin(e) {
	// e.target 是图形对象，即数据的可视化对象;
	// 图形对象的 refDataID 属性是数据（feature）的 id 属性，它指明图形对象是由那个数据制作而来;
	// 图形对象的 dataInfo 属性是图形对象表示的具体数据，他有两个属性，field 和 value;
	if (e.target && e.target.refDataID && e.target.dataInfo) {
		closeInfoWin();
		// 获取图形对应的数据 (feature)
		var fea = faultThemeLayer.getFeatureById(e.target.refDataID);

		var info = e.target.dataInfo;

		// 弹窗内容
		var contentHTML = "<div style='color: #000; background-color: #fff'>";
		contentHTML += "省级行政区名称:<br><strong>" + fea.attributes.NAME
				+ "</strong>";

		contentHTML += "<hr style='margin: 3px'>";
		switch (info.field) {
		case "CON2009":
			contentHTML += "09年故障发生<strong>" + info.value
					+ "</strong>（次）";
			break;
		case "CON2010":
			contentHTML += "10年故障发生<strong>" + info.value
					+ "</strong>（次）";
			break;
		case "CON2011":
			contentHTML += "11年故障发生<strong>" + info.value
					+ "</strong>（次）";
			break;
		case "CON2012":
			contentHTML += "12年故障发生<strong>" + info.value
					+ "</strong>（次）";
			break;
		case "CON2013":
			contentHTML += "13年故障发生<strong>" + info.value
					+ "</strong>（次）";
			break;
		default:
			contentHTML += "No Data";
		}
		contentHTML += "</div>";

		// 弹出框大小
		var infowinSize = (SuperMap.Browser.name == "firefox") ? new SuperMap.Size(
				150, 105)
				: new SuperMap.Size(200, 90);

		// 弹出窗地理位置
		var lonLat = map.getLonLatFromPixel(infowinPosition);
		infowin = new SuperMap.Popup("infowin", lonLat, infowinSize,
				contentHTML, false, false, null);
		infowin.setBackgroundColor("#fff");
		infowin.setOpacity(0.8);
		if (infowin)
			map.removePopup(infowin);
		map.addPopup(infowin);
	}
}


//构建 feature 数据, 专题图的数据必须是 SuperMap.Feature.Vector
function addBarThemeLayer() {
	clearThemeLayer();
	if(themeLayerShow){
		themeLayerShow = false;
		return;
	}
	createBarFaultLayer();
	var features = [];
	for ( var i = 0, len = chinaConsumptionLevel.length; i < len; i++) {
		// 省居民消费水平（单位：元）信息
		var provinceInfo = chinaConsumptionLevel[i];
		var geo = new SuperMap.Geometry.Point(provinceInfo[1],
				provinceInfo[2]);
		var attrs = {};
		attrs.NAME = provinceInfo[0];
		attrs.CON2009 = provinceInfo[3];
		attrs.CON2010 = provinceInfo[4];
		attrs.CON2011 = provinceInfo[5];
		attrs.CON2012 = provinceInfo[6];
		attrs.CON2013 = provinceInfo[7];

		var fea = new SuperMap.Feature.Vector(geo, attrs);
		features.push(fea);
	}

	faultThemeLayer.addFeatures(features);
	 map.addLayers([faultThemeLayer]);
	 themeLayerShow = true;
}
function openProtectResponse(){
	var ps = [];
	var params = MyModal.getModalParam("/ui/dataview/protect/responseFeaDialog.xhtml", "1200", null,ps);
	openDialog(params);
}

document.oncontextmenu = function(evt) {
	return false;
};

// 按钮的二级菜单
$("#btnBoxLeft li").mouseover(function (){
	if($.contains(this,this.getElementsByTagName("ul")[0])){
		$("#btnBoxRight").css("display","none");
	}
});
$("#btnBoxLeft li").mouseout(function (){
	if($.contains(this,this.getElementsByTagName("ul")[0])){
		$("#btnBoxRight").css("display","block");
	}
});
